package org.raymond.iworks.study.mq.rabbitmq.classic.dlx;

import com.rabbitmq.client.*;
import com.rabbitmq.client.impl.DefaultExceptionHandler;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
@Slf4j
public class NormalWithDLXWorker {

    public static String EXCHANGE_NAME = "ex";
    public static String QUEUE_NAME = "queue";
    public static String ROUTING_KEY = "rk";
    private static String DLX_EXCHANGE_NAME = "dlx_ex";
    private static String DLX_ROUTING_NAME = "dlx_rk";

    /**
     * 进入死信交换机的触发条件:
     * 1, nack或reject,并且requeue为false的消息
     * 2, 过期(不包括队列过期)的消息
     * 3, 队列溢出的消息
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        Connection conn = connection();
        Channel channel = conn.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);

        Map<String, Object> map = new HashMap<>();
        map.put("x-dead-letter-exchange", DLX_EXCHANGE_NAME);
        map.put("x-dead-letter-routing-key", DLX_ROUTING_NAME);
        map.put("x-message-ttl", 10*1000); // 消息过期时间,针对ready状态的消息,即还在消息队列中,才适用过期时间
        channel.queueDeclare(QUEUE_NAME, true, false, false, map);
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY);
        log.info("[*] Waiting for message");

        channel.basicQos(1);

        Consumer consumer = new DefaultConsumer(channel){
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                                       byte[] body) throws IOException {
                String message = new String(body, StandardCharsets.UTF_8);
                log.info(" [x] Received {}:{}", envelope.getRoutingKey(), message);
                if(message.startsWith("ioexception")){
                    // Close due to exception from Consumer xx method handleDelivery for channel
                    throw new IOException("any io exception");
                }else if(message.startsWith("exception")){
                    throw new RuntimeException("any exception");
                }
                //测试消费者中抛出异常的影响:默认异常处理器会close channel.
                //测试消费者中开子线程的影响:子线程独自执行,消费者线程继续执行
                if(message.startsWith("thread")){
                    new Thread(()->{
                        log.info("sub thread start.");
                        // 耗时操作放入子线程
                        try {
                            Thread.sleep(10*1000);
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                        log.info("sub thread done.");
                    }).start();
                }
                try{
                    doWork(message);
                }catch (InterruptedException e){
                    log.error("{}: {} will intterrupt.", e.getMessage(), Thread.currentThread().getName());
                    Thread.currentThread().interrupt();
                }finally {
                    log.info(" [x] Done");
                    boolean multiple = false;
                    boolean requeue = false;
                    // 当nack或reject时, 消费者可以不停的收到reject消息,然后因为requeue=false而转发到死信交换器上
                    // 正常消息无影响,直接消费掉,不会转发到DLX
                    long deliveryTag = envelope.getDeliveryTag();
                    if(message.startsWith("nack")) {
                        channel.basicNack(deliveryTag, multiple, requeue);
                    }else if(message.startsWith("reject")){
                        channel.basicReject(deliveryTag, requeue);
                    }else{
                        channel.basicAck(deliveryTag, multiple);
                    }
                }
            }
        };

        boolean autoAck = false;
        channel.basicConsume(QUEUE_NAME, autoAck, consumer);
    }

    private static void doWork(String task) throws InterruptedException {
        if(task.startsWith("interrupted")){
            Thread.currentThread().interrupt();
        }
        for (char ch: task.toCharArray()){
            if(ch=='.') Thread.sleep(1000);
        }
    }

    public static Connection connection() throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.0.125");
        factory.setPort(5672);
        factory.setUsername("cloud");
        factory.setPassword("cloud123");
        factory.setVirtualHost("/cloud");

        factory.setExceptionHandler(new DefaultExceptionHandler(){
            @Override
            public void handleConsumerException(Channel channel, Throwable exception, Consumer consumer, String consumerTag, String methodName) {
                super.handleConsumerException(channel, exception, consumer, consumerTag, methodName);
                log.info("consumer exception: {}", exception.getMessage());
            }
        });
        return factory.newConnection();
    }
}
